package com.paul.common.utils.Sign;

import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author ZMK
 * @date 2022/12/19 15:04
 * @description
 */
public class RSASignUtil {

    /**
     * 签名
     *
     * @param privateKey 私钥
     * @param text       明文
     * @return
     */
    public static String sign(String privateKey, String text, String inputCharset) {
        byte[] signed = null;
        try {
            Signature Sign = Signature.getInstance("SHA256WithRSA");
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey.getBytes()));
            KeyFactory kf = KeyFactory.getInstance("RSA");
            PrivateKey priKey = kf.generatePrivate(priPKCS8);
            Sign.initSign(priKey);
            Sign.update(text.getBytes(inputCharset));
            signed = Sign.sign();
        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return Base64.encodeBase64String(signed);
    }


    /**
     * 验签
     *
     * @param publicKey    公钥
     * @param text         明文
     * @param inputCharset 编码
     * @param signed       签名
     */
    public static boolean verify(String publicKey, String text, String inputCharset, String signed) {

        boolean SignedSuccess = false;
        try {
            Signature verifySign = Signature.getInstance("SHA256WithRSA");
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decodeBase64(publicKey);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
            verifySign.initVerify(pubKey);
            verifySign.update(text.getBytes(inputCharset));
            SignedSuccess = verifySign.verify(Base64.decodeBase64(signed));

        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return SignedSuccess;
    }
}
